package com.jcvision.mms.controller;

import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jcvision.mms.dao.SubscriberDao;
import com.jcvision.mms.model.Subscriber;
import com.jcvision.mms.model.SubscriberExample;
import com.jcvision.mms.util.Constant;
import com.jcvision.mms.util.ErrorMsg;
import com.jcvision.mms.util.MobileRegion;
import com.jcvision.mms.util.PageBean;

@Controller
@RequestMapping("/module/subscriber")
public class SubscriberController extends BaseController {

	@SuppressWarnings("unchecked")
	@RequestMapping("/list.do")
	public String list(Subscriber subscriber, Integer pageNumber, ModelMap map){
		try{
			SubscriberExample subscriberExample = new SubscriberExample();
			if(subscriber != null && subscriber.getMobileNumber() != null){
				subscriber.setMobileNumber(new String(subscriber.getMobileNumber().getBytes("iso-8859-1"), "UTF-8"));
				subscriberExample.createCriteria().andMobileNumberLike("%" + subscriber.getMobileNumber() + "%");
			}
			PageBean pageBean = new PageBean();
			if(pageNumber != null){
				pageBean.setCurrentPage(pageNumber);
			}
			
			SubscriberDao subscriberDao = new SubscriberDao();
			List<Subscriber> rows = (List<Subscriber>) subscriberDao.select(subscriberExample, pageBean);
			
			map.put("pageBean", pageBean);
			map.put("rows", rows);
			map.put("stateMap", Constant.stateMap);
			return "forward:/module/subscriber/list.jsp";
		}catch(Exception e){
			e.printStackTrace();
			map.put(ERROR_KEY, ErrorMsg.DAO_EXCEPTION);
			return ERROR_PAGE;
		}
	}
	
	@RequestMapping("/updateLocale.do")
	@ResponseBody
	public String updateLocale(Long id) {
		if(id != null){
			SubscriberDao subscriberDao = new SubscriberDao();
			Subscriber subscriber = (Subscriber) subscriberDao.select(id);
			if(subscriber != null && subscriber.getMobileNumber() != null && !"".equals(subscriber.getMobileNumber().trim())) {
				MobileRegion mr = new MobileRegion();
				Map<String, String> searchMap = mr.search(subscriber.getMobileNumber().trim());
				if(searchMap != null){
					if(searchMap.get("Province") != null && searchMap.get("City") != null) {
						String locale = searchMap.get("Province") + searchMap.get("City");
						subscriber.setLocale(locale);
					}
				}
			}
			
			try {
				subscriberDao.updateByPrimaryKeySelective(subscriber);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
}
